package com.yuhang.zhimitest.util;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * created by zhangyuhang on 2018/6/26
 */
public class GsonUtil {

    public static void main(String args[]){

        test1();
        test2();
        test3();
        test4();
        test5();
    }

    //基本数据类型的解析
    public static void test1(){
        Gson gson = new Gson();
        int i = gson.fromJson("100", int.class);              //100
        double d = gson.fromJson("\"99.99\"", double.class);  //99.99
        boolean b = gson.fromJson("true", boolean.class);     // true
        String str = gson.fromJson("String", String.class);
        System.out.println("=====基本数据类型的解析=====");
        System.out.println("i >>"+i);
        System.out.println("d >>"+d);
        System.out.println("b >>"+b);

    }

    //基本数据类型的生成
    public static void test2(){
        Gson gson = new Gson();
        String jsonNumber = gson.toJson(100);       // 100
        String jsonBoolean = gson.toJson(false);    // false
        String jsonString = gson.toJson("String"); //"String"

        System.out.println("====基本数据类型的生成====");
        System.out.println("jsonNumber  >>"+jsonNumber);
        System.out.println("jsonBoolean  >>"+jsonBoolean);
        System.out.println("jsonString  >>"+jsonString);
    }

    //POJO类的生成与解析
    public static String test3(){

        Gson gson = new Gson();
        User user = new User("怪盗kidou",24,"359294760@qq.com");
        String jsonObject = gson.toJson(user);
        System.out.println("=====从pojo生成成为jsonstring =====");
        System.out.println("jsonObject >>>"+jsonObject);
        return jsonObject;

    }

    //json解析成为pojo
    public static void test4() {

        //获得string字符串
        Gson gson = new Gson();
        String jsonStr = test3();
        User user = gson.fromJson(jsonStr,User.class);
        System.out.println("=====json解析成为pojo =====");
        System.out.println("user>>>"+ user);
    }

    //使用token来解析json
    public static void test5() {

        //获得string字符串
        Gson gson = new Gson();
        String jsonStr = test3();
        User user = gson.fromJson(jsonStr,new TypeToken<User>(){}.getType());
        System.out.println("=====使用token来解析json =====");
        System.out.println("user>>>"+ user);
    }
}
